import os

import requests

class WxWorkSms:
    # header = {"Content-Type": "multipart/form-data"}
    headers = {"Content-Type": "application/json"}
    # key ='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ff6fcd5-5525-4a33-90e8-07589e188fa6'
    # key ='3ff6fcd5-5525-4a33-90e8-07589e188fa6'

    def __init__(self, key):
        self.send_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}"
        self.up_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={key}&type=file"

    def send_markdown_with_history(self, current_data, history_data=None):
        """
        发送包含历史对比的Markdown消息
        :param current_data: 当前运行数据
        :param history_data: 历史运行数据（可选）
        """
        # 格式化当前数据
        content = (
            f"**提醒！自动化测试反馈**\n"
            f"#### 请相关同事注意，及时跟进！\n\n"
            f"项目名称：<font color=\"info\">{current_data['project_name']}</font>\n"
            f"项目指定端：<font color=\"info\">{current_data['project_port']}</font>\n"
            f"测试用例总数：<font color=\"info\">{current_data['total']}</font>；"
            f"测试用例通过率：<font color=\"info\">{current_data['pass_rate']:.2f}%</font>\n"
            f"------------------运行详情------------------\n"
            f"> **成功数：**<font color=\"info\">{current_data['passed']}</font>\n"
            f"> **失败数：**<font color=\"warning\">{current_data['failed']}</font>\n"
            f"> **错误数：**<font color=\"info\">{current_data['broken']}</font>\n"
            f"> **跳过数：**<font color=\"info\">{current_data['skipped']}</font>\n"
        )

        # 如果有历史数据，添加对比
        if history_data:
            content += (
                f"\n------------------上一次运行结果------------------\n"
                f"测试用例总数：{history_data['total']}\n"
                f"测试用例通过率：{history_data['pass_rate']:.2f}%\n"
                f"成功数：**<font color=\"info\">{history_data['passed']}</font>\n"
                f"失败数：**<font color=\"info\">{history_data['failed']}</font>\n"
                f">错误数：**<font color=\"info\">{history_data['broken']}</font>\n"
                f"跳过数：**<font color=\"info\">{history_data['skipped']}</font>\n"
            )

        # 添加报告链接（如果有）
        if 'report_url' in current_data and current_data['report_url']:
            content += f"\n> #### 报告链接：[点击后进入查看]({current_data['report_url']})"

        # 发送消息
        send_data = {
            "msgtype": "markdown",
            "markdown": {"content": content}
        }
        response = requests.post(self.send_url, json=send_data, headers=self.headers)
        return response.json()
    def send_markdown(self, project_name,project_port, total_cases, pass_rate, success_cases, fail_cases, skip_cases):
        """
        发送Markdown消息
        """
        send_markdown_data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"**提醒：自动化测试反馈**\n#### 请相关同事注意，及时跟进！\n"
                           f"> 项目名称：<font color=\"info\">{project_name}</font>\n"
                           f"> 项目指定端：<font color=\"info\">{project_port}</font>\n"
                           f"> 测试用例总数：<font color=\"info\">{total_cases}</font>；测试用例通过率：<font color=\"info\">{pass_rate}</font>\n"
                           f">------------------运行详情------------------\n"
                           f"> **成功数：**<font color=\"info\">{success_cases}</font>\n**失败数：**<font color=\"warning\">{fail_cases}</font>\n"
                           f"> **跳过数：**<font color=\"info\">{skip_cases}</font>\n"


            }
        }
        response = requests.post(self.send_url, json=send_markdown_data, headers=self.headers)
        return response.json()

    def send_file(self, file_path):
        """
        发送文件（支持 Excel、ZIP、HTML 等）
        :param file_path: 文件路径
        """
        if os.path.isdir(file_path):
            # 如果是目录，默认发送 index.html
            file_path = os.path.join(file_path, "index.html")
        if not os.path.exists(file_path):
            return {"error": "文件不存在"}

        with open(file_path, 'rb') as file:
            files = {'media': file}  # 企业微信要求字段名为 'media'
            response = requests.post(self.up_url, files=files)

        # 如果上传成功，发送文件消息
        if response.status_code == 200:
            media_id = response.json().get("media_id")
            if media_id:
                return self._send_file_message(media_id)
        return response.json()

    def _send_file_message(self, media_id):
        """内部方法：发送文件消息"""
        send_data = {
            "msgtype": "file",
            "file": {"media_id": media_id}
        }
        response = requests.post(self.send_url, json=send_data, headers=self.headers)
        return response.json()

    def send_report(self, report_path):
        """
        发送测试报告（自动判断文件类型）
        :param report_path: 报告路径（可以是文件或目录）
        """
        if os.path.isdir(report_path):
            # 如果是目录，默认发送目录下的 index.html（Allure 报告）
            report_path = os.path.join(report_path, "index.html")

        return self.send_file(report_path)